<template>
  <div>
    <a-modal
      id="poster"
      v-model="visible"
      title="上传答案模块图"
      ok-text="保存"
      cancel-text="取消"
      @ok="save"
      @cancel="cancel"
    >
      <a-spin
        :spinning="loading"
        tip="loading...."
        class="maxDiv"
        oncontextmenu="return false"
        onselectstart="return false"
        ondragstart="return false"
      >
        <div class="show_area" ref="area">
          <!-- 图标开关 -->
          <div class="switch">
            <a-switch
              :checked="showCode"
              @change="showCode = !showCode;"
              :disabled="photo.img[0]==null?true:false"
            />
            <span>二维码</span>
            <a-switch
              :checked="showHead"
              @change="showHead = !showHead;"
              :disabled="photo.img[0]==null?true:false"
            />
            <span>头像</span>
          </div>
          <!-- 图片显示与图标摆放位置 -->
          <div class="poster_container">
            <div class="photo_wrap">
              <div class="no_img" v-if="!photo.img[0]">请点击上传图片</div>
              <img v-else class="poster" :src="photo.img[photo.index]" alt />
              <!-- 移动二维码 -->
              <VueDragResize
                :w="codeInfo.len"
                :h="codeInfo.len"
                v-on:resizing="resize1"
                v-on:dragging="resize1"
                v-if="photo.img[0]==null?false:true"
                :style="{top:codeInfo.Y+'px',left:codeInfo.X+'px'}"
              >
                <img
                  v-show="showCode"
                  class="code"
                  :src="photo.code"
                  alt
                  :width="codeInfo.len"
                  :height="codeInfo.len"
                />
              </VueDragResize>
              <!-- 移动头像 -->
              <VueDragResize
                :w="headInfo.len"
                :h="headInfo.len"
                v-on:resizing="resize2"
                v-on:dragging="resize2"
                v-if="photo.img[0]==null?false:true"
                :style="{top:headInfo.Y+'px',left:headInfo.X+'px'}"
              >
                <img
                  v-show="showHead"
                  class="head"
                  :src="photo.head"
                  alt
                  :width="headInfo.len"
                  :height="headInfo.len"
                />
              </VueDragResize>
            </div>
          </div>
        </div>
        <!-- 当前移动的位置数据 -->
        <ul class="parameter">
          <li>
            <span>x：</span>
            <a-input-number v-model="paramInfo.X" :min="0" />
          </li>
          <li>
            <span>y：</span>
            <a-input-number v-model="paramInfo.Y" :min="0" />
          </li>
          <li>
            <span>边长：</span>
            <a-input-number v-model="paramInfo.len" :min="0" />
          </li>
        </ul>
        <!-- 上传图片 -->
        <div class="list">
          <swiper ref="mySwiper" :options="swiperOptions">
            <swiper-slide v-for="(item ,index) in photo.img" :key="index">
              <div class="room_img">
                <img :src="item" @click="handleImgIndex(index)" />
                <span @click="delete_img(index)">
                  <img src="@/assets/delete.png" />
                </span>
              </div>
            </swiper-slide>
            <swiper-slide>
              <div class="room_add_img">
                <span>
                  <img src="@/assets/add_img.png" />
                </span>
                <span>上传图片</span>
                <!--  -->
                <input @change="add_img" type="file" ref="upload1" accept="image/png,image/jpeg,image/jpg"/>
              </div>
            </swiper-slide>
          </swiper>
        </div>
      </a-spin>
    </a-modal>
  </div>
</template>
<script>
import { Swiper, SwiperSlide } from "vue-awesome-swiper";
import { getOssPolicy, postImageTemplate } from "@/api/paper";
import VueDragResize from "vue-drag-resize";
import axios from "axios";
import Vue from "vue";
export default {
  components: {
    Swiper,
    SwiperSlide,
    VueDragResize
  },
  props: ["visible2"],
  data() {
    return {
      loading: false,
      visible: "",
      updatePoster: [],
      //  图片
      photo: {
        index: 0,
        img: [],
        code: require("@/assets/qrcode.png"),
        head: require("@/assets/avatar.png")
      },
      //  二维码数据
      showCode: false,
      codeInfo: {
        X: 0,
        Y: 0,
        len: 50
      },
      //  头像数据
      showHead: false,
      headInfo: {
        X: 0,
        Y: 0,
        len: 50
      },
      //  显示参数数据
      paramInfo: {
        X: 0,
        Y: 0,
        len: 50
      },
      headORcode: -1,
      //  swiper 参数
      swiperOptions: {
        slidesPerView: "auto",
        freeMode: true,
        direction: "vertical"
      }
    };
  },
  watch: {
    visible2: {
      handler(value) {
        this.visible = value;
      },
      immediate: true
    },
    showCode: {
      handler(value) {
        if (value == false) {
          let arr = {
            X: 0,
            Y: 0,
            len: 50
          };
          this.codeInfo = arr;
        }
      },
      immediate: true
    },
    showHead: {
      handler(value) {
        if (value == false) {
          let arr = {
            X: 0,
            Y: 0,
            len: 50
          };
          this.headInfo = arr;
        }
      },
      immediate: true
    },
    paramInfo: {
      handler(value) {
        // console.log(value)
        if (this.headORcode == 0) {
          this.codeInfo = JSON.parse(JSON.stringify(value));
          // this.codeInfo = value;
          Vue.set(this.codeInfo, value);
        } else if (this.headORcode == 1) {
          this.headInfo = JSON.parse(JSON.stringify(value));
          // this.headInfo = value;
          Vue.set(this.headInfo, value);
        }
      },
      immediate: true,
      deep: true
    }
  },
  computed: {
    swiper() {
      return this.$refs.mySwiper.$swiper;
    }
  },
  methods: {
    //  放大缩小移动
    resize1(newRect) {
      this.codeInfo.X = newRect.left;
      this.codeInfo.Y = newRect.top;
      this.codeInfo.len = newRect.width;
      this.paramInfo.X = newRect.left;
      this.paramInfo.Y = newRect.top;
      this.paramInfo.len = newRect.width;
      this.headORcode = 0;
    },
    resize2(newRect1) {
      this.headInfo.X = newRect1.left;
      this.headInfo.Y = newRect1.top;
      this.headInfo.len = newRect1.width;
      this.paramInfo.X = newRect1.left;
      this.paramInfo.Y = newRect1.top;
      this.paramInfo.len = newRect1.width;
      this.headORcode = 1;
    },

    //  删除海报事件
    delete_img(item) {
      this.photo.img.splice(item, 1);
      this.updatePoster.splice(item,1)
    },
    //  添加海报事件
    async add_img(event) {
      var img1 = event.target.files[0];
      var _this = this;
      _this.$refs.upload1.setAttribute("type", "text");
      await getOssPolicy({})
        .then(response => {
          var uploadObj;
          if (response.data == undefined) {
            uploadObj = response;
          } else {
            uploadObj = response.data;
          }
          let host = uploadObj.host;
          var request = new FormData();

          var arrIndex = img1.name.split(".").length - 1;
          var imgExit = img1.name.split(".")[arrIndex];
          var rand = Math.floor(Math.random() * 10);
          var rand1 = _this.getCode();
          var ossName = rand1 + "_" + rand + "." + imgExit;

          request.append("OSSAccessKeyId", uploadObj.accessid); //Bucket 拥有者的Access Key Id。
          request.append("policy", uploadObj.policy); //policy规定了请求的表单域的合法性
          request.append("Signature", uploadObj.signature); //根据Access Key Secret和policy计算的签名信息，OSS验证该签名信息从而验证该Post请求的合法性
          request.append("key", `${uploadObj.dir}${ossName}`); //文件名字，可设置路径
          request.append("success_action_status", 200); // 让服务端返回200,不然，默认会返回204
          request.append("file", img1); //需要上传的文件 file

          var imgurl = host + "/" + uploadObj.dir + ossName;
          let config = {
            headers: {
              "Content-Type": "application/octet-stream"
            }
          };
          axios
            .post(host, request, config)
            .then(function(res) {
              _this.$refs.upload1.setAttribute("type", "file");
              _this.loading = true;
              console.log(res);
              _this.photo.img.push(imgurl);
              _this.updatePoster = [];
              for (let i = 1; i <= _this.photo.img.length; i++) {
                // var j = _length + i;
                var j = i;
                let data = {
                  positionNum: j,
                  id: "card" + j,
                  name: "1",
                  imgUrl: _this.photo.img[i - 1],
                  tmplId: ""
                };
                _this.updatePoster.push(data);
                _this.loading = false;
                _this.showCode = true;
                _this.showHead = true;
              }
            })
            .catch(err => {
              _this.$message.error(err);
              _this.loading = false;
              _this.$refs.upload1.setAttribute("type", "file");
            });
        })
        .catch(err => {
          _this.$message.error(err);
          _this.loading = false;
          _this.$refs.upload1.setAttribute("type", "file");
        });
    },
    //  切换海报事件
    handleImgIndex(index) {
      this.photo.index = index;
    },
    // 保存
    save() {
      var _this = this;
      // let config = {
      //   headers: {
      //     "Access-Token": "oohmEwvbcIxQQCDASY7BSdsiUrrg"
      //   }
      // };
      let avatar = Object.values(this.headInfo);
      if (avatar[0] == 0 && avatar[1] == 0 && _this.showHead == false) {
        avatar[2] = 0;
      }
      avatar.splice(3, 1, avatar[2]);
      let qrcode = Object.values(this.codeInfo);
      if (qrcode[0] == 0 && qrcode[1] == 0 && _this.showCode == false) {
        qrcode[2] = 0;
      }
      qrcode.splice(3, 1, qrcode[2]);
      let request = {
        imgUrls: this.photo.img,
        avatarPosi: avatar,
        qrcodePosi: qrcode
      };
      console.log(request);
      let img_url = this.photo.img[0];
      let img = new Image();
      img.src = img_url;
      // console.log(img.width);
      // console.log(img.height);
      // console.log(avatar)
      // console.log(qrcode)
      let rate = img.width / 350;

      postImageTemplate({
        imgUrls: this.photo.img,
        avatarPosi: [
          Number((avatar[0] * rate).toFixed(0)),
          Number((avatar[1] * rate).toFixed(0)),
          Number((avatar[2] * rate).toFixed(0)),
          Number((avatar[3] * rate).toFixed(0))
        ],
        qrcodePosi: [
          Number((qrcode[0] * rate).toFixed(0)),
          Number((qrcode[1] * rate).toFixed(0)),
          Number((qrcode[2] * rate).toFixed(0)),
          Number((qrcode[3] * rate).toFixed(0))
        ]
        // avatarPosi:avatar,
        // qrcodePosi:qrcode
      })
        .then(res => {
          if (res.data) {
            for (var i = 0; i < _this.updatePoster.length; i++) {
              _this.updatePoster[i]["tmplId"] = res.data["tmplId"];
            }
            var _img = [];
            _this.photo.img = _img;
            _this.$emit("UpdatePoster", false, _this.updatePoster);
            _this.$message.success("保存成功");
            _this.showHead = false;
            _this.showCode = false;
          }
        })
        .catch(err => {
          _this.$message.error(err);
          _this.loading = false;
        });
    },
    //取消给父组件响应
    cancel() {
      this.$emit("UpdatePoster");
    },
    // 随机码
    getRandom(min, max) {
      return Math.round(Math.random() * (max - min) + min);
    },
    getCode() {
      var _this = this;
      let code = "";
      for (var i = 0; i < 6; i++) {
        var type = _this.getRandom(1, 3);
        switch (type) {
          case 1:
            code += String.fromCharCode(_this.getRandom(48, 57)); //数字
            break;
          case 2:
            code += String.fromCharCode(_this.getRandom(65, 90)); //大写字母
            break;
          case 3:
            code += String.fromCharCode(_this.getRandom(97, 122)); //小写字母
            break;
        }
      }
      return code;
    }
  }
};
</script>
<style lang="less" scoped>
#poster /deep/ .ant-modal {
  width: 50% !important;
  min-width: 900px !important;
  max-width: 1000px !important;
  min-height: 700px !important;
  top: 30px;
  font-family: "Franklin Gothic Medium", "Arial Narrow", Arial, sans-serif;
  .ant-modal-close-x {
    height: 40px;
    line-height: 40px;
  }
  .ant-modal-body {
    padding: 14px 24px;
    position: relative;
  }
  .swiper-container {
    height: 100%;
    padding-top: 15px;
    padding-bottom: 15px;
    .swiper-slide {
      height: auto;
    }
  }
}
/deep/ .maxDiv {
  display: inline-block;
  width: 100%;
  .show_area {
    vertical-align: top;
    top: 0px;
    width: 40%;
    background-color: white;
    opacity: 1;
    display: inline-block;
    .switch {
      display: flex;
      align-items: center;
      font-size: 20em;
      font-weight: 600;
      span {
        font-size: 16px;
        margin: 0 15px 0 4px;
      }
    }
    .poster_container {
      display: inline-block;
      .photo_wrap {
        position: relative;
        width: 350px;
        overflow: hidden;
        display: inline-block;

        .no_img {
          font-size: 20px;
          line-height: 200px;
          text-align: center;
          font-weight: 500;
        }
        img:nth-child(1) {
          width: 100%;
        }
        img:nth-child(2),
        img:nth-child(3) {
          position: absolute;
        }
      }
    }
  }
  .parameter {
    vertical-align: top;
    display: inline-block;
    width: 40%;
    height: 100%;
    list-style: none;
    > li {
      margin: 20px 50% 0 0;
      float: right;
    }
  }
  .list {
    vertical-align: top;
    // position:absolute;
    display: inline-block;
    right: 0;
    top: 0;
    width: 20%;
    height: 100%;
    .room_img {
      top: 0px;
      width: 150px;
      height: 100px;
      position: relative;
      overflow: hidden;
      img {
        width: 100%;
        height: 100%;
      }
      span {
        position: absolute;
        width: auto;
        height: auto;
        right: 5px;
        bottom: 3px;
      }
    }
    .room_add_img {
      width: 148px;
      height: 98px;
      border: 1px solid #e1e1e1;
      box-sizing: content-box;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: space-between;
      position: relative;
      > span:nth-child(1) {
        margin-top: 20px;
        width: 40px;
        height: 40px;
        overflow: hidden;
      }
      > span:nth-child(2) {
        margin-bottom: 10px;
      }
      input {
        position: absolute;
        top: 0px;
        left: 0px;
        width: 100%;
        height: 100%;
        z-index: 99999;
        opacity: 0;
      }
    }
  }
}
</style>